// 引入二维码生成器
const QRCodeHelper = require('../../utils/qrcode-helper.js').default;

Page({
  data: {
    qrCodeUrl: 'https://api-v2.jianzhugang.com/app/nameCard/getMiniAppQrCode?id=13444',
    inputValue: 'https://example.com',
    isGenerating: false
  },

  onLoad: function() {
    // 页面加载时显示默认图片
    // 不需要自动生成二维码
  },

  // 输入框内容变化
  onInputChange: function(e) {
    this.setData({
      inputValue: e.detail.value
    });
  },

  // 生成二维码
  generateQRCode: function() {
    const { inputValue } = this.data;
    if (!inputValue) {
        wx.showToast({
            title: '请输入内容',
            icon: 'none'
        });
        return;
    }

    this.setData({ isGenerating: true });
    wx.showLoading({ title: '生成中...' });

    // 生成二维码
    this.generateQRCodeDirectly(inputValue);
  },

  // 点击图片预览
  previewImage: function() {
    const { qrCodeUrl } = this.data;
    if (qrCodeUrl) {
      wx.previewImage({
        urls: [qrCodeUrl],
        current: qrCodeUrl
      });
    }
  },

  // 生成二维码并预览
  generateQRCodeDirectly: function(text) {
    const query = wx.createSelectorQuery();
    query.select('#temp-qrcode-canvas')
      .fields({ node: true, size: true })
      .exec((res) => {
        if (!res || !res[0]) {
          wx.hideLoading();
          this.setData({ isGenerating: false });
          wx.showToast({
            title: 'Canvas节点获取失败',
            icon: 'none'
          });
          return;
        }

        const canvas = res[0].node;
        const ctx = canvas.getContext('2d');
        
        // 设置Canvas尺寸
        const size = 300;
        canvas.width = size;
        canvas.height = size;

        // 清空画布
        ctx.clearRect(0, 0, size, size);
        
        // 设置背景
        ctx.fillStyle = '#ffffff';
        ctx.fillRect(0, 0, size, size);

        // 生成二维码数据
        const qrCodeHelper = new QRCodeHelper();
        qrCodeHelper.setSize(size, size);
        qrCodeHelper.setEccLevel(2);
        
        try {
          const qrData = qrCodeHelper.generateQRCode(text);
          const moduleCount = require('../../utils/qrcode.js').api.size;
          const moduleSize = size / moduleCount;

          // 绘制二维码
          ctx.fillStyle = '#000000';
          for (let row = 0; row < moduleCount; row++) {
            for (let col = 0; col < moduleCount; col++) {
              if (qrData[col * moduleCount + row]) {
                ctx.fillRect(
                  col * moduleSize,
                  row * moduleSize,
                  moduleSize,
                  moduleSize
                );
              }
            }
          }

          // 使用canvasToTempFilePath生成临时文件
          wx.canvasToTempFilePath({
            canvas: canvas,
            width: size,
            height: size,
            destWidth: size,
            destHeight: size,
            fileType: 'png',
            quality: 1,
            success: (res) => {
              wx.hideLoading();
              console.log('二维码生成成功', res.tempFilePath);
              
              this.setData({
                qrCodeUrl: res.tempFilePath,
                isGenerating: false
              });

              // 自动预览二维码
              wx.previewImage({
                urls: [res.tempFilePath],
                current: res.tempFilePath
              });
            },
            fail: (error) => {
              wx.hideLoading();
              console.error('canvasToTempFilePath失败', error);
              this.setData({ isGenerating: false });
              wx.showToast({
                title: '生成失败，请重试',
                icon: 'none'
              });
            }
          });
        } catch (error) {
          wx.hideLoading();
          console.error('二维码绘制失败', error);
          this.setData({ isGenerating: false });
          wx.showToast({
            title: '生成失败，请重试',
            icon: 'none'
          });
        }
      });
  }
});